package dao

import (
	"gopkg.in/yaml.v2"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"io/ioutil"
	"log"

	"fmt"
)

type Conf struct {
	MySQL MySQLConf `yaml:"mysql"`
	Redis RedisConf `yaml:"redis"`
}

type MySQLConf struct {
	Url        string `yaml:"url"`
	UserName   string `yaml:"username"`
	Password   string `yaml:"password"`
	DbName     string `yaml:"dbname"`
	Port       string `yaml:"port"`
	AvatarPath string `yaml:"avatarPath"`
}

var SqlSession *gorm.DB

func (c *Conf) getConf() *Conf {
	yamlFile, err := ioutil.ReadFile("resources/application.yaml")
	if err != nil {
		fmt.Printf("can't find the yaml file %v", err)
	}
	err = yaml.Unmarshal(yamlFile, c)
	if err != nil {
		fmt.Printf(err.Error())
	}
	return c
}

// 头像存储地址
func (c *Conf) GetAFPath() string {
	getConf := c.getConf()
	ap := getConf.MySQL.AvatarPath
	return ap
}

// 初始化mysql连接
func InitMySQL() (err error) {
	var c Conf
	conf := c.getConf()
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		conf.MySQL.UserName,
		conf.MySQL.Password,
		conf.MySQL.Url,
		conf.MySQL.Port,
		conf.MySQL.DbName,
	)
	SqlSession, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic(err)
	}
	// 检查数据库连接是否正常
	err = SqlSession.Exec("SELECT 1").Error
	if err != nil {
		panic(err)
	}

	fmt.Println("MySQL connection successful!")
	return nil
}

// 关闭mysql
func CloseMySQL() {
	db, err := SqlSession.DB()
	if err != nil {
		log.Panicf("关闭MySQL失败: %v", err)
	}
	err = db.Close()
	if err != nil {
		return
	}
	fmt.Println("成功关闭MySQL。")
}
